import axios from "axios"
import router from "../router/index"

axios.defaults.timeout = 10000;
const instance = axios.create({
  // baseURL:
});

instance.interceptors.request.use(config => {
  // const token = sessionStorage.getItem("token");

  return config;
}, error => {
  return Promise.reject(error);
});

instance.interceptors.response.use(res => {

  if(res.data.token) sessionStorage.setItem("token",res.data.token);

  return res;
}, error => {
  const _response = error.response

  switch(_response.status) { // 判断 HTTP 状态码
    case 401:
      // token 验证失败
      sessionStorage.removeItem('token')
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath // 跳转之前，将原本想访问的路径保存在 query
        }
      })
      break
    case 404:
      console.err('资源不存在')
      break
    case 408:
      console.err('请求超时了')
      break
    case 500:
      console.err('服务器错误')
      break
  }

  return Promise.reject(error);
});


export default instance;